package com.css.fxfzypg.modules.message.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.modules.message.repository.MessageRepository;
import com.css.fxfzypg.modules.message.repository.entity.MessageEntity;
import com.css.fxfzypg.modules.message.repository.entity.MessagePageList;
import com.css.fxfzypg.modules.preassesstaskmanage.vo.PreAssessVo;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

@Repository
public class MessageRepositoryImpl implements MessageRepository {
    @Resource
    public JdbcTemplate jdbcTemplate;

    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public boolean addMessage(MessageEntity messageEntity) {
        String sql = "INSERT INTO public.ypg_message " +
                "(message_id, message_system, message_generator, message_receiver, message_content, " +
                "message_remarks, message_status,message_create_user,message_create_time," +
                "del_flag) " +
                "VALUES (:messageId, :messageSystem, :messageGenerator, :messageReceiver, :messageContent, :messageRemarks, :messageStatus, :messageCreateUser, :messageCreateTime, :delFlag)";
        SqlParameterSource source = new BeanPropertySqlParameterSource(messageEntity);
        //拿到新插入的主键值（i）
        KeyHolder keyHolder = new GeneratedKeyHolder();
        int i = namedParameterJdbcTemplate.update(sql, source, keyHolder);
        if(i>0){
            return true;
        }
        return false;
    }

    @Override
    public MessagePageList queryMessage(String keyWords,String userId, int currentPage, int pageSize) {
        MessagePageList pageList = new MessagePageList(currentPage,pageSize);
        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append("SELECT * FROM ypg_message where del_flag = '0' ");
        if (StringUtils.isNotBlank(keyWords)){
            sql.append("and message_content like '%"+keyWords +"%' ");
        }
        if (StringUtils.isNotBlank(userId)){
            sql.append("and message_receiver = ? ");
            sql.append("order by message_status,message_create_time desc");
            params.add(userId);
        }
        List<MessageEntity> list = jdbcTemplate.query(sql.toString(),new BeanPropertyRowMapper<>(MessageEntity.class),userId);
        pageList.setAllNumber(list.size());
        if(pageList.getCurrentPage()==pageList.getPageNumber()){
            pageList.setMessageList(jdbcTemplate.query(sql.toString() + " limit ? OFFSET ?",new BeanPropertyRowMapper<>(MessageEntity.class),userId,pageSize,(currentPage-1)*pageSize));
        }else{
            pageList.setMessageList(jdbcTemplate.query(sql.toString() + " limit ? OFFSET ?",new BeanPropertyRowMapper<>(MessageEntity.class),userId,pageSize,(currentPage-1)*pageSize));
        }
        return pageList;
    }

    @Override
    public MessageEntity getMessageById(String messageId) {
        StringBuffer sql = new StringBuffer();
        MessageEntity messageEntity = new MessageEntity();
        sql.append("SELECT * FROM ypg_message where del_flag = '0' ");
        if (StringUtils.isNotBlank(messageId)){
            sql.append("and message_id = ? ");
        }
        messageEntity = jdbcTemplate.queryForObject(sql.toString(), new BeanPropertyRowMapper<>(MessageEntity.class),messageId);
        return messageEntity;
    }

    @Override
    public boolean readMessage(MessageEntity messageEntity) {
        messageEntity.setMessageStatus("1");
        messageEntity.setMessageUpdateUser(PlatformSessionContext.getUserID());
        messageEntity.setMessageUpdatetime(new Date());
        String sql = "update ypg_message set message_status = ? where message_id = ?";
        Object args[] = {messageEntity.getMessageStatus(),messageEntity.getMessageId()};
        int temp = jdbcTemplate.update(sql, args);
        if(temp > 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean clearMessage(String userId) {
        StringBuffer sql = new StringBuffer();
        sql.append("update ypg_message set message_status = '1' where message_receiver = ?");
        int temp = jdbcTemplate.update(sql.toString(),userId);
        if (temp > 0 ){
            return true;
        }
        return false;
    }

    @Override
    public boolean readMessageByModel(String messageModel) {
        StringBuffer sql = new StringBuffer();
        sql.append("update ypg_message set message_status = '1' where message_model = ?");
        int temp = jdbcTemplate.update(sql.toString(),messageModel);
        if (temp > 0 ){
            return true;
        }
        return false;
    }

    @Override
    public List<MessageEntity> getMessage(String userId) {
        StringBuilder sql = new StringBuilder("SELECT * FROM ypg_message  ");
        StringBuilder whereSql = new StringBuilder(" where del_flag = '0' and message_status = '0'");
        StringBuilder orderSql = new StringBuilder(" order by message_status,message_create_time desc");
        StringBuilder countSql = new StringBuilder(" select count(message_id) from ypg_message");
        if (!PlatformObjectUtils.isEmpty(userId)) {
            whereSql.append(" and message_receiver = '"+userId+"'");
        }
        String sqlWhole = sql.append(whereSql).append(orderSql).toString();
        countSql.append(whereSql);
        List<MessageEntity> list = jdbcTemplate.query(sqlWhole, new BeanPropertyRowMapper<>(MessageEntity.class));
        return list;
    }
}
